import { useMenuStore, useTabStore } from '@/stores'
import { useRoute, useRouter } from 'vue-router'
import { breakpointsTailwind, useBreakpoints } from '@vueuse/core'

export const defaultLayout = () => {
  const menuStore = useMenuStore()
  const tabStore = useTabStore()
  const router = useRouter()
  const route = useRoute()

  /**
   * keep-alive includes
   */
  const kaIncludes = computed(() => tabStore.tabs.map(({ kaName }) => kaName))

  /**
   * tab
   */
  const onTabChange = (name: string) => {
    tabStore.tabActive = name
    router.push({ name, query: { ...tabStore.tab?.query }, params: { ...tabStore.tab?.params } })
  }

  const onTabRemove = (name: string) => {
    tabStore.close(name)
    router.push({
      name: tabStore.tabActive,
      query: { ...tabStore.tab?.query },
      params: { ...tabStore.tab?.params }
    })
  }

  // bug fixed @tab-change="tabChange" tab-change 事件只有点击 tab 才会触发，不会监听 v-model 变化
  watchEffect(() => {
    const name = tabStore.tabActive
    const tab = tabStore.tabs.find((tab) => tab.name === name)
    if (tab?.source === 'menu') {
      menuStore.menuActive = name
    } else if (tab?.menu) {
      menuStore.menuActive = tab.menu
    }
  })

  onMounted(() => {
    // 刷新后，跳转到 tabStore.tabActive 对应的页面
    if (route.name !== tabStore.tabActive) {
      router.push({
        name: tabStore.tabActive,
        query: { ...tabStore.tab?.query },
        params: { ...tabStore.tab?.params }
      })
    }
  })

  /**
   * 屏幕断点
   */
  const breakpoints = useBreakpoints(breakpointsTailwind)
  // 小于等于 1024px 都会 true
  const lgAndSmaller = breakpoints.smallerOrEqual('lg')
  watch(lgAndSmaller, (b) => (menuStore.collapse = b), { immediate: true })

  return {
    kaIncludes,
    onTabChange,
    onTabRemove
  }
}
